<template>
  <div class="funds">
    <div class="tabs-header">
      <!-- 实时资金 -->
      <div
        class="tab"
        :class="{'active': tabActive === 1}"
        @click="switchTab(1)"
      >{{$t('trade.realTimeFunds')}}</div>
      <!-- 资金流水 -->
      <div
        class="tab"
        :class="{'active': tabActive === 2}"
        @click="switchTab(2)"
      >{{$t('trade.capitalFlow')}}</div>
      <!-- 资金流水操作 -->
      <div class="handle-group" v-if="tabActive === 2">
        <span class="label">{{$t('trade.date')}}:</span>
        <date-picker
          :value="tiemRange"
          format="yyyy-MM-dd"
          type="daterange"
          placement="bottom-end"
          :placeholder="$t('trade.seldate')"
          @on-change="dealDateTime"
          style="width: 200px;"
        ></date-picker>
        <i-select
          v-model="currency"
          :placeholder="$t('trade.seltype')"
          style="width:200px; margin-left: 20px;"
        >
          <i-option v-for="item in moneyList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
        </i-select>
        <div>
          <span class="btn mt16" @click="initCapitalFlow(1)">{{$t('tip.search')}}</span>
          <span class="btn" @click="handleDownload(pdfName)">{{$t('tip.export')}}</span>
        </div>
      </div>
    </div>
    <div class="tabs-content">
      <div class="tab1" v-show="tabActive === 1">
        <!-- 实时资金 -->
        <div class="table-box" v-for="(item, i) in moneylist" :key="i + 'currency'">
          <table border="0" cellspacing="0" cellpadding="0" class="dTable j-table">
            <tbody>
              <tr class="tableTxt">
                <td>{{$t('capital.currency')}}：{{item.currencyId === 1 ? '人民币' : (item.currencyId === 3 ? '美元' : '港币')}}</td>
                <td>{{$t('capital.bookmoney')}}：{{item.accountBalance}}</td>
                <td>{{$t('capital.capitalinterest')}}：{{parseFloat(parseFloat(item.accountBalance) - parseFloat(item.frozenAmount) + parseFloat(item.floatPL)).toFixed(2)}}</td>
                <!-- 账面资金 + 逐笔浮盈 -->
              </tr>
              <tr class="tableTxt">
                <td>
                  {{$t('capital.computedDetailProfitAndLoss')}}：{{parseFloat(item.floatPL).toFixed(2)}}
                  <span></span>
                </td>
                <!-- 盯市浮盈 -->
                <!-- <td>
                  {{$t('capital.computedDetailMarket')}}：
                  <span></span>
                </td>-->
                <!-- 自有权益 -->
                <!--<td>{{$t('capital.selfEquity')}}：</td> -->
                <td>{{$t('capital.frozenAmount')}}：{{item.frozenAmount}}</td>
                <td></td>
              </tr>
              <tr class="tableTxt">
                <td>{{$t('capital.totalMargin')}}：{{item.occupationMargin}}</td>
                <td>{{$t('capital.enableWithdrawBalance')}}：{{parseFloat(parseFloat(item.accountBalance) - parseFloat(item.frozenAmount) + parseFloat(item.floatPL) -parseFloat(item.riskFund)).toFixed(2)}}</td>
                <td></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="tab2" v-show="tabActive === 2">
        <table border="0" cellspacing="0" cellpadding="0" class="dTable" id="flow_table">
          <thead>
            <tr>
              <th>{{$t('market.time')}}</th>
              <th>{{$t('bank.amount')}}</th>
              <th>{{$t('capital.currency')}}</th>
              <th>{{$t('trade.type')}}</th>
              <th>{{$t('trade.balance')}}</th>
              <th>{{$t('trade.signNo')}}</th>
            </tr>
          </thead>
          <tbody>
            <!-- 无数据时展示 -->
            <tr v-if="capitalFlowList.length === 0" class="noneInfo">
              <td>{{$t('msg.noData')}}</td>
            </tr>
            <!-- 数据列表 -->
            <tr
              v-else
              v-for="(item, index) in capitalFlowList"
              :key="item.FlowId"
              :class="{active: actIndex === index}"
              @click="switchTr(index)"
            >
              <td>
                <div v-if="item.DateTime">{{item.DateTime}}</div>
                <div v-else>---</div>
              </td>
              <td>
                <div v-if="item.FlowSum !== undefined">{{item.FlowSum}}</div>
                <div v-else>---</div>
              </td>
              <td>
                <div v-if="item.Currency">{{item.Currency}}</div>
                <div v-else>---</div>
              </td>
              <td>
                <div v-if="item.FlowType">{{item.FlowType}}</div>
                <div v-else>---</div>
              </td>
              <td>
                <div v-if="item.Balance !== undefined">{{item.Balance}}</div>
                <div v-else>---</div>
              </td>
              <td>
                <div v-if="item.SingleNo">{{item.SingleNo}}</div>
                <div v-else>---</div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { DatePicker, Select, Option } from "iview";
import * as trade from "../../../request/trade";
import { setTimeout } from "timers";
import moment from "moment";
moment.locale("zh-cn");
export default {
  name: "FundStatus",
  components: {
    DatePicker,
    ISelect: Select,
    IOption: Option
  },
  computed: {
    lang() {
      return this.$store.getters.lang;
    },
    userinfo() {
      return this.$store.getters.userinfo;
    },
    moneylist() {
    	let temp_moneylist = this.$store.getters.moneylist.filter( (e) =>{
    		return  e.currencyId==3;
    	});
    	return temp_moneylist;
    },
    capitalFlowList() {
      return this.$store.getters.capitalflowlist;
    }
  },
  watch: {
    lang(val) {
      if(!val) {
        return;
      }
      let list = [
        {
          value: "0",
          label: this.$t("tip.all")
        },
        {
          value: "1",
          label: this.$t("menu.RMB")
        },
        {
          value: "3",
          label: this.$t("menu.USD")
        }
      ];
      this.moneyList = list;
    },
    capitalFlowList(val) {
      this.pdfName = moment(new Date()).format('YYYY-MM-DD HH:mm');
    }
  },
  mounted() {
    setTimeout(()=>{
      this.initCapitalFlow();
    },3000)
  },
  data() {
    let nowDate = moment(new Date()).format('YYYY-MM-DD');
    let list = [
      {
        value: "0",
        label: this.$t("tip.all")
      },
      {
        value: "1",
        label: this.$t("menu.RMB")
      },
      {
        value: "3",
        label: this.$t("menu.USD")
      }
    ];
    return {
      tabActive: 1,
      tiemRange: [nowDate, nowDate],
      moneyList: list,
      currency: "0", // 当前选中的币种下拉1人民币3美元
      actIndex: -1,
      pdfName: moment(new Date()).format('YYYY-MM-DD HH:mm'),
      downloadLoading: false
    };
  },
  methods: {
    switchTab(i) {
      this.tabActive = i;
    },
    switchTr(i) {
      // table行选中
      this.actIndex = i;
    },
    dealDateTime(val, type) {
      // console.log(val)
      this.tiemRange = val;
    },
    initCapitalFlow(flag) {
      // 初始化资金流水
      // console.log(this.tiemRange);
      // let stratDate = new Date(this.tiemRange[0]);
      // let endDate = new Date(this.tiemRange[1]);
      // stratDate = Date.parse(stratDate) / 1000;
      // endDate = Date.parse(endDate) / 1000;
      let userId = this.userinfo.uId; // 用户id
      let stratDate = new Date(this.tiemRange[0] + " 00:00:00");
      let endDate = new Date(this.tiemRange[1] + " 23:59:59");
      stratDate = Math.round(Date.parse(stratDate) / 1000).toString();
      endDate = Math.round(Date.parse(endDate) / 1000).toString();
      // this.currency // 币种
      // 发送：45;用户ID;开始时间;截止时间;币种;
      // console.log(
      //   `45;${userId};${parseInt(stratDate)};${parseInt(endDate)};${
      //     this.currency
      //   };`
      // );
      if(flag === 1) this.$store.dispatch("panel/playTipsAudio", 6);
      // this.$store.dispatch("bar/changeLoadings", {
      //   msg: this.$t("tip.placeWait1"),
      //   status: true
      // });
      trade.wsSend(
        `45;${userId};${parseInt(stratDate)};${parseInt(endDate)};${
          this.currency
        };`
      );
    },
    handleDownload() {
      if (this.capitalFlowList.length === 0) {
        that.$store.dispatch("bar/switchAlert", {
          title: this.$t("tip.tip"),
          msg: this.$t("tip.fowNone"),
          type: 2
        });
        return;
      }
      if (this.downloadLoading) {
        return;
      }
      this.$store.dispatch("panel/playTipsAudio", 6);
      this.downloadLoading = true;
      let nowDate = moment().format("YYYY-MM-DD");
      let nowTime = moment().format("HH:mm:ss");
      nowDate = nowDate.split("-");
      nowTime = nowTime.split(":");
      let fileName = nowDate.join("") + nowTime.join("");
      // console.log(fileName)

      import("@/utils/Export2Excel").then(excel => {
        const tHeader = [
          this.$t("market.time"),
          this.$t("bank.amount"),
          this.$t("capital.currency"),
          this.$t("trade.type"),
          this.$t("trade.balance"),
          this.$t("trade.signNo")
        ];
        const filterVal = [
          "DateTime",
          "FlowSum",
          "Currency",
          "FlowType",
          "Balance",
          "SingleNo"
        ];
        const list = this.capitalFlowList;
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: fileName,
          autoWidth: true,
          bookType: "xlsx"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          return v[j];
        })
      );
    }
  }
};
</script>

<style lang="scss">
.funds {
  .tabs-header {
    .handle-group {
      .ivu-date-picker {
        .ivu-date-picker-rel {
          .ivu-input-wrapper {
            .ivu-input-suffix {
              i {
                line-height: 22px;
              }
            }
            .ivu-input {
              height: 22px;
            }
          }
        }
      }
      .ivu-select {
        .ivu-select-selection {
          height: 22px;
          .ivu-select-placeholder {
            height: 22px;
            line-height: 22px;
          }
          .ivu-select-selected-value {
            height: 22px;
            line-height: 22px;
          }
        }
      }
    }
  }
}
</style>


<style lang="scss" scoped>
.funds {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  padding-left: 2px;
  .tabs-content {
    .tab1 {
      height: 100%;
      border: 1px solid #b1bbc0;
      border-right: 0;
      overflow-y: auto;
      .table-box {
        display: inline-block;
        width: 50%;
        height: 102px;
        padding: 6px;
        .dTable {
          tbody {
            height: 100%;
            border: 1px solid #b1bbc0;
            padding-bottom: 2px;
            tr {
              border-bottom: 1px solid #b1bbc0;
              &:nth-last-of-type(1) {
                border-bottom: none;
              }
              td {
                border-right: 1px solid #b1bbc0;
                line-height: 28px;
                height: 28px;
                &:nth-last-of-type(1) {
                  border-right: none;
                }
              }
            }
          }
        }
      }
    }
    .tab2 {
      height: 100%;
      border: 1px solid #b1bbc0;
      border-right: 0;
    }
  }
}
</style>
